from rest_framework import serializers
from django.core.paginator import Paginator,EmptyPage
from users.models import User
from django.contrib.auth.hashers import make_password


# class UserSerializer(serializers.Serializer):
#     page = serializers.IntegerField(label="页数")
#     pagesize = serializers.IntegerField(label="每页个数")
#     keyword = serializers.CharField(allow_null=True,label="关键字")
#
#     def validate(self, attrs):
#         page = attrs["page"]
#         pagesize = attrs["pagesize"]
#         keyword = attrs.get("keyword")
#         if keyword:
#             user_qs = User.objects.filter(is_staff=True,username__contains=keyword)
#         else:
#             user_qs = User.objects.filter(is_staff=True)
#         user_qs = user_qs.order_by("id")
#         paginator = Paginator(object_list=user_qs, per_page=pagesize)
#         try:
#             page_list = paginator.page(page)
#         except EmptyPage:
#             raise serializers.ValidationError("页数超最大值")
#         lists = []
#         for user in page_list:
#             lists.append({
#                 "id": user.id,
#                 "username": user.username,
#                 "mobile": user.phone_number,
#                 "email": user.email
#             })
#         return {
#             "count":len(user_qs),
#             "page":page,
#             "pagesize":pagesize,
#             "page_list":lists,
#             "pages":paginator.num_pages
#         }
#
#
# class CreateUserSerializer(serializers.ModelSerializer):
#     class Meta:
#         fields = "__all__"
#         model = User
#
#     def validate(self, attrs):
#         pass
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        fields = ("id","username","phone_number","email","password")
        model = User

        extra_kwargs = {
            "password": {"write_only": True},

        }

    def validate(self, attrs):
        attrs["password"] = make_password(attrs["password"])
        attrs["is_staff"] = True

        return attrs







